package com.example.noteback.student.controller;


import com.example.noteback.student.domain.Student;
import com.example.noteback.student.service.impl.StudentServiceImpl;
import com.example.noteback.upload.excel.ExcelUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("student")
public class StudentController {
    @Autowired
    private StudentServiceImpl studentService;

    @RequestMapping("/file")
    public String file(){
        return "file";
    }
    @PostMapping("/upload")
    @ResponseBody
    public String uploadFile(@RequestParam("file") MultipartFile file) throws Exception {
        try {
            // 上传文件路径
            String filePath = "E:\\DATA\\SHIXUN2\\data\\";
            String fileName=System.currentTimeMillis()+file.getOriginalFilename();

            // 上传文件
            File f=new File(filePath+fileName);
            file.transferTo(f);
            fileName=filePath+fileName;
            //输入流
            FileInputStream fileInputStream = new FileInputStream(new File(fileName));
            List<List<Object>> list = ExcelUtils.getListByExcel(fileInputStream, fileName);
            List<Object> firstRows = null;
            List<Student> studentList=new ArrayList<>();
            if (list != null && list.size() > 0) {
                firstRows = list.get(0);
            }else {
                return "failure";
            }
            for (int i = 1; i < list.size(); i++) {
                List<Object> rows = list.get(i);
                Student student = new Student();
                for (int j = 0; j < rows.size(); j++) {
                    String cellVal = (String) rows.get(j);
                    ExcelUtils.setFileValueByFieldName(student, firstRows.get(j).toString().trim(), cellVal);
                }
                studentList.add(student);
            }
            Integer flag=this.studentService.batchInsert(studentList);
            if(flag!=0){
                return "ok";
            }else {
                return "failure";
            }

        } catch (Exception e) {
            return "failure";
        }
    }
}
